{/* LAYOUT模板 */}
	<layout name="layout"/>
{/* LAYOUT模板 */}

{/* import Js,Css */}
	<js href="__PUBLIC__/js/admin/listTable.js"/>
	<js href="__PUBLIC__/js/admin/js.util.js"/>
	<js href="__PUBLIC__/js/admin/js.validator.js"/>
	<js href="__PUBLIC__/js/admin/js.selectzone.js"/>
	<css href="__PUBLIC__/css/admin/admin.css"/>
	
	<css href="__PUBLIC__/css/jquery-ui.css" />
	<js href="__PUBLIC__/js/core/jquery-ui.1.10.4.js" />
	<js href="__PUBLIC__/js/core/plugins.js"/>
	<js href="__PUBLIC__/js/core/jquery.json-2.2.js"/>
{/* import js,css */}

<!-- [position] -->
	<include file="Template:position"/>
<!-- [position] -->

<div id="loading" class="hide"><!--Qloading:不能删除--></div>

<style>
#tab{margin-left:2px; margin-bottom:-2px;}#tab ul li{list-style:none;}#tab li{border:1px solid #b5e2f3;border-bottom:0px;float:left;width:100px;height:25px;margin:0 -1px;background:#F1FEF3;padding:9px 0 0 0;text-align:center;color:#33a3dc;cursor:pointer;}#tab ul{width:800px;height:36px;border-bottom:1px solid #b5e2f3;/*border-bottom:1px solid #b5e2f3;*/}#tab #selected{background:#FFF!important;border-bottom:2px solid #FFF!important;}ul{margin:-1px;}#cate1,#cate2, #cate3, #cate4, #cate5{clear:both;height:300px;background:#FFFFFF;width:800px;height:100px;padding:25px;height:auto;border:1px solid #b5e2f3;}
</style>

<form name="theForm" method="post" action="__APP__/goods/add_goods_ok" enctype="multipart/form-data">
	<div class="mauto b" style="width:80%">
		<div id="tab" >
			<ul>
				<li tar="cate1" id="selected">通用信息</li>
				<li tar="cate2">详细描述</li>
				<li tar="cate3">其他信息</li>
				<li tar="cate4">商品属性</li>
				<li tar="cate5">商品相册</li>
				<li tar="cate6">关联商品</li>
				<li tar="cate7">配件</li>
				<li tar="cate8">关联文章</li>
			</ul>
		</div>
		<div>
			<div id="cate1" style="display:block;">
				<include file="Goods:1"/>
			</div>
			<div id="cate2" style="display:none;">
				<include file="Goods:2"/>
			</div>
			<div id="cate3" style="display:none;">
				<include file="Goods:3"/>
			</div>
			<div id="cate4" style="display:none;">
				<include file="Goods:4"/>
			</div>
			<div id="cate5" style="display:none;">
				<include file="Goods:5"/>

			</div>
			<div id="cate6" style="display:none;">
				<include file="Goods:6"/>
			</div>
			<div id="cate7" style="display:none;">
				<include file="Goods:7"/>
			</div>
			<div id="cate8" style="display:none;">
				<include file="Goods:8"/>
			</div>
		</div>
		<div class="submit mb50" style="text-align:center; padding-bottom:30px;">
			<input type="hidden" name="goods_id" value="0">
			<input type="hidden" name="act" value="insert">
			<input type="button" class="qs-btn bg-green" value=" 确定 " onclick="validate('0')">
			<input type="reset" class="qs-btn" value=" 重置 " >		
		</div>	
	</div>
</form>


<script>
	/**
	* 考虑到tab和pane有可能被动态的添加和删除，
	* 所以每次都废点时间去查找先前被激活的tab
	*/
	var tab = function(tabId,activeId){
	$("#"+tabId).delegate("li:not(#"+activeId+")","click",function(){
	$("#"+$("#"+activeId).attr("tar")).css("display","none");
	$("#"+activeId).removeAttr("id");
	 
	$(this).attr("id",activeId);
	$("#"+$(this).attr("tar")).css("display","block");
	});
	};
tab("tab","selected");
</script>


<script language="JavaScript">
	var goodsId = '0'; /* 当前商品的id,若新增为0*/
	var elements = document.forms['theForm'].elements;
	var sz1 = new SelectZone(1, elements['source_select1'], elements['target_select1']);
	var sz2 = new SelectZone(2, elements['source_select2'], elements['target_select2'], elements['price2']);
	var sz3 = new SelectZone(1, elements['source_select3'], elements['target_select3']);
	var marketPriceRate = 1.2;
	var integralPercent = 1;
	var validator = new Validator('theForm');
		
	onload = function(){
		handlePromote(document.forms['theForm'].elements['is_promote'].checked);
		if (document.forms['theForm'].elements['auto_thumb']){
			handleAutoThumb(document.forms['theForm'].elements['auto_thumb'].checked);
		}
		/*startCheckOrder();*/
        set_price_note(1);
		set_price_note(3);
		set_price_note(2);            
		document.forms['theForm'].reset();
	}

	function validate(goods_id){		
		var goods_sn  = document.forms['theForm'].elements['goods_sn'].value;
		
		validator.required('goods_name', goods_name_not_null); 
		if (document.forms['theForm'].elements['cat_id'].value == 0){
			validator.addErrorMsg(goods_cat_not_null);
		}
		checkVolumeData("1",validator);

		validator.required('shop_price', shop_price_not_null);
		validator.isNumber('shop_price', shop_price_not_number, true);
		validator.isNumber('market_price', market_price_not_number, false);
		if (document.forms['theForm'].elements['is_promote'].checked){
			validator.required('promote_start_date', promote_start_not_null);
			validator.required('promote_end_date', promote_end_not_null);
			validator.islt('promote_start_date', 'promote_end_date', promote_not_lt);
		}

		if (document.forms['theForm'].elements['goods_number'] != undefined){
			validator.isInt('goods_number', goods_number_not_int, false);
			validator.isInt('warn_number', warn_number_not_int, false);
		}

		/*var callback = function(res){}*/
		/*Ajax.call('goods.php?is_ajax=1&act=check_goods_sn', "goods_sn=" + goods_sn + "&goods_id=" + goods_id, callback, "GET", "jsON");*/
		$.ajax({
			type: "get",
			url: Uri.getUri() + "/check_goods_sn",
			data:{"goods_sn":goods_sn, "goods_id":goods_id, },
			beforeSend: function(XMLHttpRequest){
				/*ShowLoading();*/
			},
			success: function(res, textStatus){
				if (res.error > 0){
					alert("您输入的货号已存在，请换一个");
				}
				else{
					if(validator.passed()){
						document.forms['theForm'].submit();
					}
				}
			},
			complete: function(XMLHttpRequest, textStatus){
				/*HideLoading();*/
			},
			error: function(){
				/*请求出错处理*/
			}
		});
	}

  /**
   * 鎸夋瘮渚嬭?绠椾环鏍
   * @param   string  inputName   杈撳叆妗嗗悕绉
   * @param   float   rate        姣斾緥
   * @param   string  priceName   浠锋牸杈撳叆妗嗗悕绉帮紙濡傛灉娌℃湁锛屽彇shop_price锛
   */
  function computePrice(inputName, rate, priceName)
  {
	
      var shopPrice = priceName == undefined ? document.forms['theForm'].elements['shop_price'].value : document.forms['theForm'].elements[priceName].value;
      shopPrice = Utils.trim(shopPrice) != '' ? parseFloat(shopPrice)* rate : 0;
	  
      if(inputName == 'integral')
      {
          shopPrice = parseInt(shopPrice);
      }
      shopPrice += "";

      n = shopPrice.lastIndexOf(".");
      if (n > -1)
      {
          shopPrice = shopPrice.substr(0, n + 3);
      }

      if (document.forms['theForm'].elements[inputName] != undefined)
      {
          document.forms['theForm'].elements[inputName].value = shopPrice;
      }
      else
      {
          document.getElementById(inputName).value = shopPrice;
      }
  }

  /**
   * 璁剧疆浜嗕竴涓?晢鍝佷环鏍硷紝鏀瑰彉甯傚満浠锋牸銆佺Н鍒嗕互鍙婁細鍛樹环鏍
   */
  function priceSetted()
  {
    computePrice('market_price', marketPriceRate);
    computePrice('integral', integralPercent / 100);
    
        set_price_note(1);
        set_price_note(3);
        set_price_note(2);
        
  }

  /**
   * 璁剧疆浼氬憳浠锋牸娉ㄩ噴
   */
  function set_price_note(rank_id)
  {
    var shop_price = parseFloat(document.forms['theForm'].elements['shop_price'].value);

    var rank = new Array();
    
        rank[1] = 100;
        rank[3] = 90;
        rank[2] = 95;
        
    if (shop_price >0 && rank[rank_id] && document.getElementById('rank_' + rank_id) && parseInt(document.getElementById('rank_' + rank_id).value) == -1)
    {
      var price = parseInt(shop_price * rank[rank_id] + 0.5) / 100;
      if (document.getElementById('nrank_' + rank_id))
      {
        document.getElementById('nrank_' + rank_id).innerHTML = '(' + price + ')';
      }
    }
    else
    {
      if (document.getElementById('nrank_' + rank_id))
      {
        document.getElementById('nrank_' + rank_id).innerHTML = '';
      }
    }
  }

  /**
   * 技术市场价
   */
  function marketPriceSetted()
  {
    computePrice('shop_price', 1/marketPriceRate, 'market_price');
    computePrice('integral', integralPercent / 100);
    
        set_price_note(1);
        set_price_note(3);
        set_price_note(2);
        
  }

  /**
   * 鏂板?涓€涓??鏍
   */
  function addSpec(obj)
  {
      var src   = obj.parentNode.parentNode;
      var idx   = rowindex(src);
      var tbl   = document.getElementById('attrTable');
      var row   = tbl.insertRow(idx + 1);
      var cell1 = row.insertCell(-1);
      var cell2 = row.insertCell(-1);
      var regx  = /<a([^>]+)<\/a>/i;

      cell1.className = 'label';
      cell1.innerHTML = src.childNodes[0].innerHTML.replace(/(.*)(addSpec)(.*)(\[)(\+)/i, "$1removeSpec$3$4-");
      cell2.innerHTML = src.childNodes[1].innerHTML.replace(/readOnly([^\s|>]*)/i, '');
  }

  /**
   * 鍒犻櫎瑙勬牸鍊
   */
  function removeSpec(obj)
  {
      var row = rowindex(obj.parentNode.parentNode);
      var tbl = document.getElementById('attrTable');

      tbl.deleteRow(row);
  }

  /**
   * 澶勭悊瑙勬牸
   */
  function handleSpec()
  {
      var elementCount = document.forms['theForm'].elements.length;
      for (var i = 0; i < elementCount; i++)
      {
          var element = document.forms['theForm'].elements[i];
          if (element.id.substr(0, 5) == 'spec_')
          {
              var optCount = element.options.length;
              var value = new Array(optCount);
              for (var j = 0; j < optCount; j++)
              {
                  value[j] = element.options[j].value;
              }

              var hiddenSpec = document.getElementById('hidden_' + element.id);
              hiddenSpec.value = value.join(String.fromCharCode(13));
          }
      }
      return true;
  }

  function handlePromote(checked)
  {
      document.forms['theForm'].elements['promote_price'].disabled = !checked;
      /*document.forms['theForm'].elements['selbtn1'].disabled = !checked;
      document.forms['theForm'].elements['selbtn2'].disabled = !checked;*/
	  
  }

  function handleAutoThumb(checked)
  {
      document.forms['theForm'].elements['goods_thumb'].disabled = checked;
      document.forms['theForm'].elements['goods_thumb_url'].disabled = checked;
  }

  /**
   *
   */
  function rapidBrandAdd(conObj)
  {
      var brand_div = document.getElementById("brand_add");

      if(brand_div.style.display != '')
      {
          var brand =document.forms['theForm'].elements['addedBrandName'];
          brand.value = '';
          brand_div.style.display = '';
      }
  }

	function hideBrandDiv(){
		/*var brand_add_div = document.getElementById("brand_add");
		if(brand_add_div.style.display != 'none'){
			brand_add_div.style.display = 'none';
		}*/
	}

  function goBrandPage()
  {
      if(confirm(go_brand_page))
      {
          window.location.href='brand.php?act=add';
      }
      else
      {
          return;
      }
  }

  function rapidCatAdd()
  {
      var cat_div = document.getElementById("category_add");

      if(cat_div.style.display != '')
      {
          var cat =document.forms['theForm'].elements['addedCategoryName'];
          cat.value = '';
          cat_div.style.display = '';
      }
  }

  function addBrand()
  {
      var brand = document.forms['theForm'].elements['addedBrandName'];
      if(brand.value.replace(/^\s+|\s+$/g, '') == '')
      {
          alert(brand_cat_not_null);
          return;
      }

      var params = 'brand=' + brand.value;
      Ajax.call('brand.php?is_ajax=1&act=add_brand', params, addBrandResponse, 'GET', 'jsON');
  }

  function addBrandResponse(result)
  {
      if (result.error == '1' && result.message != '')
      {
          alert(result.message);
          return;
      }

      var brand_div = document.getElementById("brand_add");
      brand_div.style.display = 'none';

      var response = result.content;

      var selCat = document.forms['theForm'].elements['brand_id'];
      var opt = document.createElement("OPTION");
      opt.value = response.id;
      opt.selected = true;
      opt.text = response.brand;

      if (Browser.isIE)
      {
          selCat.add(opt);
      }
      else
      {
          selCat.appendChild(opt);
      }

      return;
  }

  // 添加分类
  function addCategory()
  {
      var parent_id = document.forms['theForm'].elements['cat_id'];
      var cat = document.forms['theForm'].elements['addedCategoryName'];
      if(cat.value.replace(/^\s+|\s+$/g, '') == '')
      {
          alert(category_cat_not_null);
          return;
      }

      var params = 'parent_id=' + parent_id.value;
      params += '&cat=' + cat.value;
      Ajax.call('category.php?is_ajax=1&act=add_category', params, addCatResponse, 'GET', 'jsON');
  }
	/* 隐藏添加分类下拉框 */
	function hideCatDiv(){
		var category_add_div = document.getElementById("category_add");
		if(category_add_div.style.display != null){
			category_add_div.style.display = 'none';
		}
	}

  function addCatResponse(result)
  {
      if (result.error == '1' && result.message != '')
      {
          alert(result.message);
          return;
      }

      var category_add_div = document.getElementById("category_add");
      category_add_div.style.display = 'none';

      var response = result.content;

      var selCat = document.forms['theForm'].elements['cat_id'];
      var opt = document.createElement("OPTION");
      opt.value = response.id;
      opt.selected = true;
      opt.innerHTML = response.cat;

      // 添加options
      var str = selCat.options[selCat.selectedIndex].text;
      var temp = str.replace(/^\s+/g, '');
      var lengOfSpace = str.length - temp.length;
      if(response.parent_id != 0)
      {
          lengOfSpace += 4;
      }
      for (i = 0; i < lengOfSpace; i++)
      {
          opt.innerHTML = '&nbsp;' + opt.innerHTML;
      }

      for (i = 0; i < selCat.length; i++)
      {
          if(selCat.options[i].value == response.parent_id)
          {
              if(i == selCat.length)
              {
                  if (Browser.isIE)
                  {
                      selCat.add(opt);
                  }
                  else
                  {
                      selCat.appendChild(opt);
                  }
              }
              else
              {
                  selCat.insertBefore(opt, selCat.options[i + 1]);
              }
              //opt.selected = true;
              break;
          }

      }

      return;
  }

    function goCatPage()
    {
        if(confirm(go_category_page))
        {
            window.location.href='category.php?act=add';
        }
        else
        {
            return;
        }
    }


  /**
   * 鍒犻櫎蹇?€熷垎绫
   */
  function removeCat()
  {
      if(!document.forms['theForm'].elements['parent_cat'] || !document.forms['theForm'].elements['new_cat_name'])
      {
          return;
      }

      var cat_select = document.forms['theForm'].elements['parent_cat'];
      var cat = document.forms['theForm'].elements['new_cat_name'];

      cat.parentNode.removeChild(cat);
      cat_select.parentNode.removeChild(cat_select);
  }

  /**
   * 鍒犻櫎蹇?€熷搧鐗
   */
  function removeBrand()
  {
      if (!document.forms['theForm'].elements['new_brand_name'])
      {
          return;
      }

      var brand = document.theForm.new_brand_name;
      brand.parentNode.removeChild(brand);
  }

  /**
   * 娣诲姞鎵╁睍鍒嗙被
   */
  function addOtherCat(conObj)
  {
      var sel = document.createElement("SELECT");
	  sel.setAttribute('class','qs-select');
      var selCat = document.forms['theForm'].elements['cat_id'];

      for (i = 0; i < selCat.length; i++)
      {
          var opt = document.createElement("OPTION");
          opt.text = selCat.options[i].text;
          opt.value = selCat.options[i].value;
          if (Browser.isIE)
          {
              sel.add(opt);
          }
          else
          {
              sel.appendChild(opt);
          }
      }
      conObj.appendChild(sel);
      sel.name = "other_cat[]";
      sel.onChange = function() {checkIsLeaf(this);};
  }




  /**
   * 鏂板?涓€涓?浘鐗
   */
  function addImg(obj)
  {
      var src  = obj.parentNode.parentNode;
      var idx  = rowindex(src);
      var tbl  = document.getElementById('gallery-table');
      var row  = tbl.insertRow(idx + 1);
      var cell = row.insertCell(-1);
      cell.innerHTML = src.cells[0].innerHTML.replace(/(.*)(addImg)(.*)(\[)(\+)/i, "$1removeImg$3$4-");
  }

  /**
   * 鍒犻櫎鍥剧墖涓婁紶
   */
  function removeImg(obj)
  {
      var row = rowindex(obj.parentNode.parentNode);
      var tbl = document.getElementById('gallery-table');

      tbl.deleteRow(row);
  }

  /**
   * 鍒犻櫎鍥剧墖
   */
  function dropImg(imgId)
  {
    Ajax.call('goods.php?is_ajax=1&act=drop_image', "img_id="+imgId, dropImgResponse, "GET", "jsON");
  }

  function dropImgResponse(result)
  {
      if (result.error == 0)
      {
          document.getElementById('gallery_' + result.content).style.display = 'none';
      }
  }

  /**
   * 灏嗗競鍦轰环鏍煎彇鏁
   */
  function integral_market_price()
  {
    document.forms['theForm'].elements['market_price'].value = parseInt(document.forms['theForm'].elements['market_price'].value);
  }

   /**
   * 灏嗙Н鍒嗚喘涔伴?搴﹀彇鏁
   */
  function parseint_integral()
  {
    document.forms['theForm'].elements['integral'].value = parseInt(document.forms['theForm'].elements['integral'].value);
  }


  /**
  * 检查商品货号是否存在
  */
	function checkGoodsSn(goods_sn, goods_id){
		if (goods_sn == ''){
			document.getElementById('goods_sn_notice').innerHTML = "";
			return;
		}

		var callback = function(res){
			
		}
		// Ajax.call('goods.php?is_ajax=1&act=check_goods_sn', "goods_sn=" + goods_sn + "&goods_id=" + goods_id, callback, "GET", "jsON");
		$.ajax({
			type: "get",
			url: Uri.getUri() + "/check_goods_sn",
			data:{"goods_sn":goods_sn, "goods_id":goods_id, },
			beforeSend: function(XMLHttpRequest){
				/*ShowLoading();*/
			},
			success: function(res, textStatus){
				if (res.error > 0){
					document.getElementById('goods_sn_notice').innerHTML = res.message;
					document.getElementById('goods_sn_notice').style.color = "red";
				}
				else{
					document.getElementById('goods_sn_notice').innerHTML = "";
				}
			},
			complete: function(XMLHttpRequest, textStatus){
				/*HideLoading();*/
			},
			error: function(){
				/*请求出错处理*/
			}
		});
	}

  /**
   * 鏂板?涓€涓?紭鎯犱环鏍
   */
  function addVolumePrice(obj)
  {
    var src      = obj.parentNode.parentNode;
    var tbl      = document.getElementById('tbody-volume');

    var validator  = new Validator('theForm');
    checkVolumeData("0",validator);
    if (!validator.passed())
    {
      return false;
    }

    var row  = tbl.insertRow(tbl.rows.length);
    var cell = row.insertCell(-1);
    cell.innerHTML = src.cells[0].innerHTML.replace(/(.*)(addVolumePrice)(.*)(\[)(\+)/i, "$1removeVolumePrice$3$4-");

    var number_list = document.getElementsByName("volume_number[]");
    var price_list  = document.getElementsByName("volume_price[]");

    number_list[number_list.length-1].value = "";
    price_list[price_list.length-1].value   = "";
  }

  /**
   * 鍒犻櫎浼樻儬浠锋牸
   */
  function removeVolumePrice(obj)
  {
    var row = rowindex(obj.parentNode.parentNode);
    var tbl = document.getElementById('tbody-volume');

    tbl.deleteRow(row);
  }

  /**
   * 鏍￠獙浼樻儬鏁版嵁鏄?惁姝ｇ‘
   */
  function checkVolumeData(isSubmit,validator)
  {
    var volumeNum = document.getElementsByName("volume_number[]");
    var volumePri = document.getElementsByName("volume_price[]");
    var numErrNum = 0;
    var priErrNum = 0;

    for (i = 0 ; i < volumePri.length ; i ++)
    {
      if ((isSubmit != 1 || volumeNum.length > 1) && numErrNum <= 0 && volumeNum.item(i).value == "")
      {
        validator.addErrorMsg(volume_num_not_null);
        numErrNum++;
      }

      if (numErrNum <= 0 && Utils.trim(volumeNum.item(i).value) != "" && ! Utils.isNumber(Utils.trim(volumeNum.item(i).value)))
      {
        validator.addErrorMsg(volume_num_not_number);
        numErrNum++;
      }

      if ((isSubmit != 1 || volumePri.length > 1) && priErrNum <= 0 && volumePri.item(i).value == "")
      {
        validator.addErrorMsg(volume_price_not_null);
        priErrNum++;
      }

      if (priErrNum <= 0 && Utils.trim(volumePri.item(i).value) != "" && ! Utils.isNumber(Utils.trim(volumePri.item(i).value)))
      {
        validator.addErrorMsg(volume_price_not_number);
        priErrNum++;
      }
    }
  }
  
</script>

